//https://leetcode.cn/problems/remove-linked-list-elements/

struct ListNode* removeElements(struct ListNode* head, int val) {

    struct ListNode* newhead = NULL, * tail = NULL;
    struct ListNode* cur = head;
    while (cur)
    {
        if (cur->val != val)
        {
            if (tail == NULL)
            {
                newhead = tail = cur;
            }
            else
            {
                tail->next = cur;
                tail = tail->next;
            }

            cur = cur->next;
        }

        else
        {
            struct ListNode* next = cur->next;
            free(cur);
            cur = next;

        }

    }

    if (tail)
    {
        tail->next = NULL;
    }

    return newhead;

}